package org.example.servletpractice.servlet;

import com.alibaba.fastjson2.JSON;
import org.example.servletpractice.mapper.WebsitesMapper;
import org.example.servletpractice.pojo.Websites;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "WebsitesServlet",value = "/websitesServlet")
public class WebsitesServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {

            // 允许所有来源访问
            resp.setHeader("Access-Control-Allow-Origin", "*");
            // 允许指定的请求方法访问
            resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            // 允许自定义的请求头部
            resp.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");

            WebsitesMapper mapper = new WebsitesMapper();
            List<Websites> websites = mapper.getWebsites();
            resp.setContentType("text/json");
            resp.setCharacterEncoding("UTF-8");
            PrintWriter writer = resp.getWriter();
            writer.println(JSON.toJSONString(websites));
            writer.flush();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
